/*
 * @Descripttion: 
 * @Mender: zhtao
 * @Date: 2020-05-21 18:45:53
 * @LastEditors: zhtao
 * @LastEditTime: 2020-06-04 10:58:08
 */
import * as API_Address from '../../api/address'
import * as API_Trade from '../../api/trade'
import { Foundation, RegExp } from '../../ui-utils/index'
let util = require('../../utils/util.js')
const App = getApp()

Page({
  data: {
    addr_id: 0,
    finished: false,
    from: '', // 页面涞源
    addressList: [],//地址列表
    isdelAddress: true,//是否显示删除框
  },
  //删除地址
  deteleAddress(e) {
    let that = this
    this.setData({
      isdelAddress: false,
      addr_id: e.currentTarget.dataset.addr_id
    })
  },
  //取消删除
  cloneDialog() {
    this.setData({ isdelAddress: true })
  },
  //确定删除
  confirmDel: util.throttle(function () {
    let that = this
    API_Address.deleteAddress(that.data.addr_id).then(() => {
      that.setData({
        isdelAddress: true
      })
      wx.showToast({ title: '删除成功' })
      that.getAddressList()
    })
  }),
  //编辑地址
  selectAddress: util.throttle(function (e) {
    let addr_id = e.currentTarget.dataset.addr_id
    wx.navigateTo({
      url: '/ucenter/addressAdd/addressAdd?addr_id=' + addr_id
    })
  }),
  //添加新地址
  addAddress: util.throttle(function (e) {
    wx.navigateTo({
      url: '/ucenter/addressAdd/addressAdd'
    })
  }),
  handleselectedaddr(e) {
    const address = e.currentTarget.dataset.address
    if (this.data.from === 'checkout') {
      API_Trade.setAddressId(address.addr_id).then(() => {
        //TODO 计算京东运费，传回去
        wx.navigateBack({ delta: 1 })
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { // 设置页面来源
    this.setData({ from: options.from || '' })
  },
  onShow() { // 获取地址列表
    this.getAddressList()
  },
  getAddressList() {
    API_Address.getAddressList().then((response) => {
      response.forEach(key => {
        key.mobile = Foundation.secrecyMobile(key.mobile)
      })
      this.setData({
        addressList: response,
        finished: true
      })
    })
  }
})